package com.superb.common.security.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.TokenSign;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.superb.common.properties.SuperbCustomProperties;
import com.superb.common.security.entity.Organization;
import com.superb.common.security.utils.SuperbUtils;
import com.superb.common.utils.HeardersUtils;
import com.superb.common.utils.StringUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: ajie
 * @CreateTime: 2024-05-15 13:19
 */
@Slf4j
public class SaTokenConfigure implements WebMvcConfigurer {

    @Resource
    private SuperbCustomProperties properties;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能
        registry.addInterceptor(new SaInterceptor().setAuth(auth -> SaRouter.match("/**")
                .notMatch(properties.getIgnoreServiceUrl().stream().map(i -> i.substring(StringUtils.getIndex("/", i, 2))).toList())
                .check(StpUtil::checkLogin)
                .check(this::setLoginUser))).addPathPatterns("/**");
    }

    /**
     * 登录用户信息赋值
     */
    private void setLoginUser() {
        SaSession session = StpUtil.getSession();
        // 1. 获取登录客户端列表
        List<TokenSign> signs = session.getTokenSignList();
        // 2. 获取当前操作客户端信息
        signs.forEach(item -> {
            if (item.getDevice().equals(HeardersUtils.getClientId())) {
                // 3. 设置客户端信息
                JSONObject tag = (JSONObject)item.getTag();
                // 最后活跃时间
                tag.put("lastActiveTime", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                // 活跃数据权限部门
                tag.put("organId", HeardersUtils.getOrganId());
                item.setTag(tag);
            }
        });
        session.setTokenSignList(signs);
        session.update();
    }

}
